<?php
declare(strict_types=1);

namespace App\Services;

use App\Models\College;
use App\Models\YikaoCollege;
use App\Models\YikaoCollegeC;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Monolog\Logger;
use Psr\Log\LoggerInterface;

class YikaoCollegeDetailSpiderService
{
    private Client $httpClient;
    private LoggerInterface $logger;
    private string $apiBaseUrl = 'https://static-data.gaokao.cn/www/2.0/school/';

    public function __construct(Client $httpClient, LoggerInterface $logger)
    {
        $this->httpClient = $httpClient;
        $this->logger = $logger;
    }

    /**
     * 获取院校详情数据
     * @param int $schoolId
     * @return array|null
     */
    public function fetchCollegeDetail(int $schoolId): ?array
    {
        $url = $this->apiBaseUrl . $schoolId . '/info.json?a=www.gaokao.cn';

        try {
            $response = $this->httpClient->get($url);
            $data = json_decode((string)$response->getBody(), true);

            if ($data['code'] !== '0000') {
                $this->logger->error('API返回错误', [
                    'school_id' => $schoolId,
                    'message' => $data['message']
                ]);
                return null;
            }

            return $data['data'];
        } catch (GuzzleException $e) {
            $this->logger->error('获取院校详情失败', [
                'school_id' => $schoolId,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * 保存院校详情数据
     * @param array $collegeData
     * @return bool
     */
    public function saveCollegeDetail(array $collegeData): bool
    {
        try {
            // 主表数据
            $mainData = $this->prepareMainData($collegeData);
            $college = YikaoCollege::query()->create($mainData);

            // 从表数据
            $detailData = $this->prepareDetailData($collegeData);
            $detailData['yikao_college_id'] = $college->id;
            YikaoCollegeC::query()->create($detailData);

            College::query()->where('school_id', $collegeData['school_id'])->update(['status' => 1]);

            return true;
        } catch (\Exception $e) {
            $this->logger->error('保存院校详情失败', [
                'school_id' => $collegeData['school_id'] ?? null,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * 准备主表数据
     * @param array $data
     * @return array
     */
    private function prepareMainData(array $data): array
    {
        return [
            'ad_level' => $data['ad_level'] ?? null,
            'address' => $data['address'] ?? null,
            'admissions' => $data['admissions'] ?? null,
            'ai_status' => $data['ai_status'] ?? null,
            'applied_grade' => $data['applied_grade'] ?? null,
            'area' => $data['area'] ?? null,
            'bdold_name' => $data['bdold_name'] ?? null,
            'belong' => $data['belong'] ?? null,
            'central' => $data['central'] ?? null,
            'city_id' => $data['city_id'] ?? null,
            'city_name' => $data['city_name'] ?? null,
            'code_enroll' => $data['code_enroll'] ?? null,
            'college_employment' => $data['college_employment'] ?? null,
            'colleges_level' => $data['colleges_level'] ?? null,
            'content' => $data['content'] ?? null,
            'coop_money' => $data['coop_money'] ?? null,
            'county_id' => $data['county_id'] ?? null,
            'create_date' => $data['create_date'] ?? null,
            'data_code' => $data['data_code'] ?? null,
            'department' => $data['department'] ?? null,
            'doctor_arr' => $data['doctor_arr'] ?? null,
            'doublehigh' => $data['doublehigh'] ?? null,
            'dual_class' => $data['dual_class'] ?? null,
            'dual_class_name' => $data['dual_class_name'] ?? null,
            'dualclass' => $data['dualclass'] ?? null,
            'e_app' => $data['e_app'] ?? null,
            'e_pc' => $data['e_pc'] ?? null,
            'email' => $data['email'] ?? null,
            'eol_rank' => $data['eol_rank'] ?? null,
            'f211' => $data['f211'] ?? null,
            'f985' => $data['f985'] ?? null,
            'fenxiao' => $data['fenxiao'] ?? null,
            'gb_show' => $data['gb_show'] ?? null,
            'gbh_num' => $data['gbh_num'] ?? null,
            'gbh_url' => $data['gbh_url'] ?? null,
            'is_ads' => $data['is_ads'] ?? null,
            'is_ads2' => $data['is_ads2'] ?? null,
            'is_evaluation' => $data['is_evaluation'] ?? null,
            'is_fenxiao' => $data['is_fenxiao'] ?? null,
            'is_international_undergraduate' => $data['is_international_undergraduate'] ?? null,
            'is_logo' => $data['is_logo'] ?? null,
            'is_recruitment' => $data['is_recruitment'] ?? null,
            'is_seal' => $data['is_seal'] ?? null,
            'is_sell' => $data['is_sell'] ?? null,
            'is_show_xcxcode' => $data['is_show_xcxcode'] ?? null,
            'is_special_project' => $data['is_special_project'] ?? null,
            'is_upgrade' => $data['is_upgrade'] ?? null,
            'is_video' => $data['is_video'] ?? null,
            'is_yikao' => $data['is_yikao'] ?? null,
            'level' => $data['level'] ?? null,
            'level_name' => $data['level_name'] ?? null,
            'master_arr' => $data['master_arr'] ?? null,
            'miniprogram' => $data['miniprogram'] ?? null,
            'motto' => $data['motto'] ?? null,
            'name' => $data['name'] ?? null,
            'nature_name' => $data['nature_name'] ?? null,
            'num_academician' => $data['num_academician'] ?? null,
            'num_doctor' => $data['num_doctor'] ?? null,
            'num_doctor2' => $data['num_doctor2'] ?? null,
            'num_lab' => $data['num_lab'] ?? null,
            'num_library' => $data['num_library'] ?? null,
            'num_master' => $data['num_master'] ?? null,
            'num_master2' => $data['num_master2'] ?? null,
            'num_subject' => $data['num_subject'] ?? null,
            'old_name' => $data['old_name'] ?? null,
            'phone' => $data['phone'] ?? null,
            'postcode' => $data['postcode'] ?? null,
            'pro_type' => $data['pro_type'] ?? null,
            'pro_type_min' => $data['pro_type_min'] ?? null,
            'province_id' => $data['province_id'] ?? null,
            'province_name' => $data['province_name'] ?? null,
            'province_score_min' => $data['province_score_min'] ?? null,
            'province_score_year' => $data['province_score_year'] ?? null,
            'province_single' => $data['province_single'] ?? null
        ];
    }

    /**
     * 准备从表数据
     * @param array $data
     * @return array
     */
    private function prepareDetailData(array $data): array
    {
        return [
            'qs_rank' => $data['qs_rank'] ?? null,
            'qs_world' => $data['qs_world'] ?? null,
            'rank' => $data['rank'] ?? null,
            'recommend_master_level' => $data['recommend_master_level'] ?? null,
            'recommend_master_rate' => $data['recommend_master_rate'] ?? null,
            'remark' => $data['remark'] ?? null,
            'ruanke_rank' => $data['ruanke_rank'] ?? null,
            'school_batch' => $data['school_batch'] ?? null,
            'school_email' => $data['school_email'] ?? null,
            'school_id' => $data['school_id'] ?? null,
            'school_nature' => $data['school_nature'] ?? null,
            'school_nature_name' => $data['school_nature_name'] ?? null,
            'school_phone' => $data['school_phone'] ?? null,
            'school_site' => $data['school_site'] ?? null,
            'school_special_num' => $data['school_special_num'] ?? null,
            'school_type' => $data['school_type'] ?? null,
            'school_type_name' => $data['school_type_name'] ?? null,
            'senior_show' => $data['senior_show'] ?? null,
            'senior_status' => $data['senior_status'] ?? null,
            'short' => $data['short'] ?? null,
            'single' => $data['single'] ?? null,
            'single_province' => $data['single_province'] ?? null,
            'single_year' => $data['single_year'] ?? null,
            'site' => $data['site'] ?? null,
            'special' => $data['special'] ?? null,
            'status' => $data['status'] ?? null,
            'subject_arr' => $data['subject_arr'] ?? null,
            'town_name' => $data['town_name'] ?? null,
            'type' => $data['type'] ?? null,
            'type_name' => $data['type_name'] ?? null,
            'upgrading_rate' => $data['upgrading_rate'] ?? null,
            'urllinks' => $data['urllinks'] ?? null,
            'us_rank' => $data['us_rank'] ?? null,
            'video' => $data['video'] ?? null,
            'video_pc' => $data['video_pc'] ?? null,
            'view_total_show' => $data['view_total_show'] ?? null,
            'vocational' => $data['vocational'] ?? null,
            'weiwangzhan' => $data['weiwangzhan'] ?? null,
            'wsl_rank' => $data['wsl_rank'] ?? null,
            'xiaoyuan' => $data['xiaoyuan'] ?? null,
            'xueke_rank' => $data['xueke_rank'] ?? null,
            'xyh_rank' => $data['xyh_rank'] ?? null,
            'xyq_id' => $data['xyq_id'] ?? null,
            'yjszs' => $data['yjszs'] ?? null,
            'yk_feature' => $data['yk_feature'] ?? null,
            'yk_type' => $data['yk_type'] ?? null,
            'zs_code' => $data['zs_code'] ?? null
        ];
    }
}
